package com.netwit.shiro.jwt.util;

import com.netwit.common.service.CommonService;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class PasswordHelper {
    private final Logger log = LoggerFactory.getLogger(PasswordHelper.class);
    private final RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    @Value("${password.algorithm.name:md5}")
    private String algorithmName;

    @Value("${password.hash.iterations:2}")
    private int hashIterations;

    public final String encryptPassword(String userid, String password, String salt) {
        String newSalt = userid + ((StringUtils.isEmpty(salt)) ? randomNumberGenerator.nextBytes().toHex() : salt);
        String result = new SimpleHash(
                (StringUtils.isEmpty(algorithmName) ? "md5" : algorithmName),
                password,
                ByteSource.Util.bytes(newSalt),
                (hashIterations <= 0 ? 2 : hashIterations)).toHex();
        return result;
    }

    public final String encryptPassword(String userid, String password) {
        Map<String, Object> user = getUser(userid);
        String salt = (String) user.get("salt");
        return encryptPassword(userid, password, salt);
    }

    @Autowired
    private CommonService commonService;
    public final Map<String, Object> getUser(String userId) {
        return commonService.getOne(new HashMap<String, Object>(){{
            put("alias", "users");
            put("whr-userCode", userId);
        }});
    }


}
